import { Card, Table, Switch, Image, Row, Col } from 'antd';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'umi';
import useConnect from '@/hooks/useConnect';
import useLoading from '@/hooks/useLoading';
import Filter from './Filter';

export default function Goods() {
  const { list, listParams } = useConnect('goods');

  const loading = useLoading('goods/getList');
  //   done -> false -> true

  //   const state = useSelector((state) => {
  //     console.log(state);
  //     return state;
  //   });
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch({
      type: 'goods/getList',
    });
  }, []);
  const columns = [
    {
      title: '商品名字',
      dataIndex: 'goodsName',
      key: 'goodsName',
      width: 400,
      render(text, record, index) {
        return (
          <div>
            <Row type="flex" align="middle">
              <Col style={{ marginRight: 10 }}>
                <Image
                  width={50}
                  height={50}
                  src={record.imageUrl}
                  fallback=""
                />
              </Col>
              <Col span={16}>
                <span>{record.goodsName}</span>
              </Col>
            </Row>
          </div>
        );
      },
    },
    {
      title: '商品价格',
      dataIndex: 'goodsPrice',
      key: 'goodsPrice',
    },
    {
      title: '商品新品',
      dataIndex: 'newStatus',
      key: 'newStatus',
      render(text, record, index) {
        // record 当前行的数据
        // record.newStatus;
        return <Switch checked={record.newStatus === '0'} />;
      },
    },
    {
      title: '商品销量',
      dataIndex: 'sellCount',
      key: 'sellCount',
    },
    {
      title: '商品评论总数',
      dataIndex: 'evalNum',
      key: 'evalNum',
    },
  ];

  return (
    <Card>
      <Filter listParams={listParams} dispatch={dispatch} />
      <Table
        loading={loading}
        dataSource={list.data}
        columns={columns}
        rowKey={(record) => record.goodsId}
        scroll={{ y: 500 }}
        pagination={{
          total: list.allCount,
          current: listParams.page,
          pageSize: listParams.everyNum,
          onChange: (page, pageSize) => {
            // 1. 改变listParams的page everyNum
            // pageSize 更改 -> page 改为 1
            if (listParams.everyNum !== pageSize) {
              page = 1;
            }
            dispatch({
              type: 'goods/updateStateProps',
              payload: {
                name: 'listParams',
                value: {
                  page: page,
                  everyNum: pageSize,
                },
              },
            });
            // 2. 请求接口
            dispatch({
              type: 'goods/getList',
            });
          },
        }}
      />
    </Card>
  );
}
